using System;
using System.Data;
using System.Transactions;
using Rhinestone.Shared;

namespace LinqRepositorySample.Data.LinqToSql
{
    public class LinqTransaction : ITransaction
    {
        #region fields
        private LinqUnitOfWork _unitOfWork;
        private TransactionScope _transaction;
        private bool _disposed;
        #endregion

        #region .ctor
        public LinqTransaction(LinqUnitOfWork unitOfWork, TransactionScope transaction)
        {
            Guard.Against<ArgumentNullException>(unitOfWork == null, "Expected a non-null unit of work.");
            Guard.Against<ArgumentNullException>(transaction == null, "Expected a non-null transaction scope.");
            _unitOfWork = unitOfWork;
            _transaction = transaction;
        }
        #endregion

        #region Implementation of IDisposable
        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        /// <filterpriority>2</filterpriority>
        public void Dispose()
        {
            if (!_disposed)
            {
                Dispose(true);
                GC.SuppressFinalize(this);
                _disposed = true;
            }
        }

        private void Dispose(bool disposing)
        {
            if (disposing)
            {
                _transaction.Dispose();
                _transaction = null;
            }
        }
        #endregion

        #region Implementation of ITransaction
        public void Commit()
        {
            _unitOfWork.Flush();
            _transaction.Complete();
            _transaction.Dispose();
        }

        public void Rollback()
        {
            _transaction.Dispose();
        }
        #endregion
    }
}